import time
import logging
from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger('action_log')


class ActionLogMiddleware(MiddlewareMixin):
    """记录带功能名称的请求日志"""

    def process_request(self, request):
        request.start_time = time.time()
        # 初始化日志元数据（防止未使用装饰器的接口报错）
        if not hasattr(request, 'log_meta'):
            request.log_meta = {'action_name': 'UNKNOWN'}

    def process_response(self, request, response):
        execution_time = time.time() - request.start_time
        # 从装饰器中提取功能名称
        action_name = request.log_meta.get('action_name', 'UNKNOWN')

        logger.info(
            "[接口日志] 功能: %s | 路径: %s | 方法: %s | 状态: %s | 耗时: %.2fs",
            action_name,
            request.path,
            request.method,
            response.status_code,
            execution_time
        )
        if request.log_meta.get('log_params'):
            logger.info("请求参数: %s", request.GET.dict() | request.POST.dict())
        return response

    def process_exception(self, request, exception):
        action_name = request.log_meta.get('action_name', 'UNKNOWN')
        logger.error(
            "[接口异常] 功能: %s | 错误: %s",
            action_name,
            str(exception),
            exc_info=True
        )
